package orphan;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;

public class OrphanTest {
	SessionFactory factory;
	
	@BeforeClass
	public void setup() {
		Configuration cfg = new Configuration();
		cfg.configure();
		
		StandardServiceRegistryBuilder servRegistryBuilder = new StandardServiceRegistryBuilder();
		servRegistryBuilder.applySettings(cfg.getProperties());
		factory = cfg.buildSessionFactory(servRegistryBuilder.build());
	}
    @Test
    public void orphanRemovalTest() {
        Long id = createLibrary();

        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();

        Library library = (Library) session.load(Library.class, id);
        System.out.println(library.getBooks().size());

        library.getBooks().remove(0);
        System.out.println(library.getBooks().size());

        tx.commit();
        session.close();

        session = factory.openSession();
        tx = session.beginTransaction();

        Library l2 = (Library) session.load(Library.class, id);
        System.out.println(l2.getBooks().size());

        Query query = session.createQuery("from Book b");
        List books = query.list();
        System.out.println(books.size());

        tx.commit();
        session.close();
    }
	
    private Long createLibrary() {
        Session session = factory.openSession();
        Transaction tx = session.beginTransaction();

        Library library = new Library();
        library.setName("orphanLib");
        session.save(library);

        Book book = new Book();
        book.setLibrary(library);
        book.setName("book 1");
        session.save(book);
        library.getBooks().add(book);

        book = new Book();
        book.setLibrary(library);
        book.setName("book 2");
        session.save(book);
        library.getBooks().add(book);

        book = new Book();
        book.setLibrary(library);
        book.setName("book 3");
        session.save(book);
        library.getBooks().add(book);

        tx.commit();
        session.close();

        return library.getId();
    }

}
